from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from base.base_page import BasePage  # 继承基础页
import allure


class ProhibitedItemsPage(BasePage):
    # 页面核心元素
    PAGE_TITLE = (AppiumBy.XPATH, "//android.widget.TextView[@text='违禁品查询']")
    SEARCH_BOX = (AppiumBy.XPATH, "//android.widget.EditText[@hint='请输入物品名称']")
    SEARCH_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='查询']")
    # 搜索建议
    SEARCH_SUGGEST = (AppiumBy.XPATH, "//android.widget.TextView[@resource-id='...suggest']")
    # 查询结果
    RESULT_BOX = (AppiumBy.XPATH, "//android.widget.LinearLayout[@resource-id='...result']")
    NO_RESULT = (AppiumBy.XPATH, "//android.widget.TextView[@text='没有找到您要查询的物品']")
    # 违禁类型标识
    AVIATION_PROHIBITED = (AppiumBy.XPATH, "//android.widget.TextView[@text='航空违禁品']")
    LAND_PROHIBITED = (AppiumBy.XPATH, "//android.widget.TextView[@text='陆运违禁品']")

    # ---------------------- 核心操作 ----------------------
    def search_item(self, keyword):
        """搜索物品（含搜索建议处理）"""
        self.click(self.SEARCH_BOX)
        self.send_keys(self.SEARCH_BOX, keyword)

        # 处理搜索建议（若有建议则选第一个）
        if self.is_element_exist(self.SEARCH_SUGGEST):
            self.click(self.SEARCH_SUGGEST)
        self.click(self.SEARCH_BTN)

    def get_result_type(self):
        """获取违禁类型（航空/陆运/无）"""
        if self.is_element_exist(self.AVIATION_PROHIBITED):
            return "航空违禁品"
        elif self.is_element_exist(self.LAND_PROHIBITED):
            return "陆运违禁品"
        else:
            return "无违禁"

    def is_result_empty(self):
        """判断是否无结果"""
        return self.is_element_exist(self.NO_RESULT)

    def get_result_message(self):
        """获取结果文本"""
        if self.is_result_empty():
            return self.find_element(self.NO_RESULT).text
        else:
            return self.find_element(self.RESULT_BOX).text

    # ---------------------- 断言辅助 ----------------------
    def assert_prohibited_type(self, expected_type):
        """验证违禁类型"""
        actual_type = self.get_result_type()
        assert actual_type == expected_type, \
            f"违禁类型不符，预期 {expected_type}，实际 {actual_type}"

    def assert_result_message(self, expected_msg):
        """验证结果文本"""
        actual_msg = self.get_result_message()
        assert expected_msg in actual_msg, \
            f"结果文本不符，预期包含 {expected_msg}，实际 {actual_msg}"